package com.xusj.pattern

/**
 * 模式匹配测试
 *
 * @author xushijian
 * @date 2020/5/18 17:50
 *
 */
object PatternTest {

  //常量匹配
  def pattern(x: Any): String = x match {
    case 0 => "zero"
    case 1 => "one"
    case _ => "other constant"
  }

  //变量匹配
  def patternVar(x: Any): String = x match {

    case 0 => "0"
    // 不是0的都匹配结果为 x: x值
    case b => s"x: $b"
  }

  // 类型匹配
  def patternType(x: Any): String = x match {
    case a: Int => "Int"
    case b: Float => "Float"
    case c: String => "String"
    case _ => "other type"
  }

  //构造器匹配
  def patternConstruction(x: Any): String = x match {
    case Person(name, age, city) => s"name: $name, age: $age, city: $city"
    case _ => "other"
  }

  //模式匹配
  def patternModal(x: Any): String = x match {

    case List(one, two, three) => s"List one: $one, two: $two, three: $three"
    // 只匹配第二个元素
    case Array(_, two, _*) => s"Array two: $two"
    case _ => "other"
  }

  def main(args: Array[String]): Unit = {


    //常量匹配
    println(pattern(1))
    println(pattern(0))
    println(pattern(2))


    //变量匹配
    println(patternVar(1))
    println(patternVar(0))
    println(patternVar(2))

    //类型匹配
    println(patternType(1))
    println(patternType("零"))
    println(patternType(2.1))

    //构造器匹配
    println(patternConstruction(Person("Bob", 18, "BeiJing")))

    //模式匹配
    println(patternModal(List("Bob", "Tom", "Jerry")))

    println(patternModal(Array("Bob", "Tom", "Jerry")))


  }
}
